package com.crionics.ghtable;

/*
 * (swing1.1beta3)
 * 
 */

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicTableHeaderUI;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GroupableTableHeaderUI extends BasicTableHeaderUI {

	private final static Logger log = LoggerFactory
			.getLogger(GroupableTableHeaderUI.class);

	private static final int DEFAULT_HEADER_HEIGHT = 20;

	@Override
	public void paint(Graphics g, JComponent c) {
	
		Rectangle clipBounds = g.getClipBounds();
		if (null == header.getColumnModel())
			return;

		GroupableTableHeader gtHeader = (GroupableTableHeader) header;

		// TODO check or remove
		gtHeader.setColumnMargin();
		@SuppressWarnings("unused")
		int columnMargin = header.getColumnModel().getColumnMargin();

		int column = 0;
		Dimension size = gtHeader.getSize();
		Rectangle cellRect = new Rectangle(0, 0, size.width, size.height);
		Hashtable<ColumnGroup, Rectangle> h = new Hashtable<ColumnGroup, Rectangle>();

		Enumeration<TableColumn> e = header.getColumnModel().getColumns();
		while (e.hasMoreElements()) {
			cellRect.height = size.height;
			cellRect.y = 0;
			TableColumn tableColumn = e.nextElement();
			List<ColumnGroup> columnGroups = gtHeader
					.getColumnGroups(tableColumn);
			if (columnGroups != null) {
				int groupHeight = 0;
				for (ColumnGroup columnGroup : columnGroups) {
					Rectangle groupRect = h.get(columnGroup);
					if (groupRect == null) {
						groupRect = new Rectangle(cellRect);
						Dimension d = columnGroup.getSize(gtHeader.getTable());
						groupRect.width = d.width;
						groupRect.height = d.height;
						h.put(columnGroup, groupRect);
					}

					paintCell(g, groupRect, columnGroup);
					groupHeight += groupRect.height;
					cellRect.height = size.height - groupHeight;
					cellRect.y = groupHeight;
				}
			}

			cellRect.width = tableColumn.getWidth();

			if (cellRect.intersects(clipBounds)) {
				paintCell(g, cellRect, column);
			}

			cellRect.x += cellRect.width;
			column++;
		}
	}

	private void paintCell(Graphics g, Rectangle cellRect, int columnIndex) {
		TableColumn column = header.getColumnModel().getColumn(columnIndex);
		TableCellRenderer renderer = column.getHeaderRenderer();

		renderer = new DefaultTableCellRenderer() {
			private static final long serialVersionUID = 6396283531577417135L;

			public Component getTableCellRendererComponent(JTable table,
					Object value, boolean isSelected, boolean hasFocus,
					int row, int column) {
				JLabel header = new JLabel();
				header.setForeground(table.getTableHeader().getForeground());
				header.setBackground(table.getTableHeader().getBackground());
				header.setFont(table.getTableHeader().getFont());

				header.setHorizontalAlignment(JLabel.CENTER);
				header.setText(value.toString());
				header.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
				return header;
			}

		};

		Component c = renderer.getTableCellRendererComponent(header.getTable(),
				column.getHeaderValue(), false, false, -1, columnIndex);

		c.setBackground(UIManager.getColor("control"));

		rendererPane.add(c);
		rendererPane.paintComponent(g, c, header, cellRect.x, cellRect.y,
				cellRect.width, cellRect.height, true);
	}

	private void paintCell(Graphics g, Rectangle cellRect,
			ColumnGroup columnGroup) {
		TableCellRenderer renderer = columnGroup.getHeaderRenderer();

		Component component = renderer.getTableCellRendererComponent(
				header.getTable(), columnGroup.getHeaderValue(), false, false,
				-1, -1);

		rendererPane.add(component);
		rendererPane.paintComponent(g, component, header, cellRect.x,
				cellRect.y, cellRect.width, cellRect.height, true);
	}

	private int getHeaderHeight() {
		int height = DEFAULT_HEADER_HEIGHT;

		TableColumnModel columnModel = header.getColumnModel();
		for (int column = 0; column < columnModel.getColumnCount(); column++) {
			TableColumn aColumn = columnModel.getColumn(column);
			TableCellRenderer renderer = aColumn.getHeaderRenderer();

			int cHeight = DEFAULT_HEADER_HEIGHT;
			if (null == renderer) {
				log.debug(aColumn.getHeaderValue() + ": renderer == null");
			} else {
				Component comp = renderer.getTableCellRendererComponent(
						header.getTable(), aColumn.getHeaderValue(), false,
						false, -1, column);

				cHeight = comp.getPreferredSize().height;
			}

			List<ColumnGroup> e = ((GroupableTableHeader) header)
					.getColumnGroups(aColumn);
			if (e != null)
				for (ColumnGroup columnGroup : e)
					cHeight += columnGroup.getSize(header.getTable()).height;

			height = Math.max(height, cHeight);
		}

		return height;
	}

	private Dimension createHeaderSize(long width) {
		log.debug("enter createHeaderSize(" + width + ")");
		TableColumnModel columnModel = header.getColumnModel();
		width += columnModel.getColumnMargin() * columnModel.getColumnCount();
		if (width > Integer.MAX_VALUE) {
			width = Integer.MAX_VALUE;
		}
		return new Dimension((int) width, getHeaderHeight());
	}

	@Override
	public Dimension getPreferredSize(JComponent c) {
		long width = 0;
		Enumeration<TableColumn> enumeration = header.getColumnModel()
				.getColumns();
		while (enumeration.hasMoreElements())
			width += enumeration.nextElement().getPreferredWidth();

		return createHeaderSize(width);
	}
}